package com.cynteka.cyfoman.ui;

import com.cynteka.cyfoman.core.config.QueryMD;
import org.jdesktop.swingx.JXTable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * User: Sergey
 * Date: 03.08.11
 * Time: 11:54
 */
public class GridWidgetFactory implements WidgetFactory {
    private EventDispatcher eventDispatcher;
    private QueryMD queryMD;

    public QueryMD getQueryMD() {
        return queryMD;
    }

    public void setQueryMD(QueryMD queryMD) {
        this.queryMD = queryMD;
    }

    @Override
    public Component createComponent() {
        final JXTable table = createTable();
        GridComparator comparator = new GridComparator();

        int count = table.getColumnCount(true);
        for (int i = 0; i < count; i++) {
            table.getColumnExt(i).setComparator(comparator);
        }

        table.setColumnControlVisible(true);
        table.getTableHeader().setVisible(true);

        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() > 1) {
                    editRow(table, queryMD);
                }
            }
        });
        table.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                if (e.getKeyChar() == KeyEvent.VK_SPACE) {
                    editRow(table, queryMD);
                }
            }
        });

        return table;
    }

    protected JXTable createTable() {
        return new StrippedTable();
    }

    public EventDispatcher getEventDispatcher() {
        return eventDispatcher;
    }

    public void setEventDispatcher(EventDispatcher eventDispatcher) {
        this.eventDispatcher = eventDispatcher;
    }

    protected void editRow(JTable table, QueryMD queryMD) {
        if (queryMD != null) {
            int row = table.getSelectedRow();
            row = table.convertRowIndexToModel(row);

            TableValueProvider tableModel = (TableValueProvider) table.getModel();
            Object entityId = tableModel.getValue(row, "id");
            if (entityId != null) {
                eventDispatcher.sendEvent(new EditEvent(queryMD.getEntityName(), entityId));
            }
        }
    }
}
